import * as Constant from '@/constant/index.js';
import * as Utils from '@/utils/index.js';

let options = null; // 页面options传参
let shareData = null; // 分享信息

// 加载初始化APP与H5交互插件
export const init = async (option = null, shareMsg = null) => {
  if (option) options = option;
  if (shareMsg) shareData = shareMsg;
  await init_one_load(option);
  watchUniJsSuccess(); //监听UniJs调用成功
  // initUniJS() //注入UniJs
};

const init_one_load = () => {
  if (options.wxlsToken) uni.setStorageSync('wxlsToken', options.wxlsToken);
};

//监听UniJs调用成功
const watchUniJsSuccess = () => {
  if (window.h5uni) {
    shareData && postMessageShare();
  } else {
    document.addEventListener('UniAppJSBridgeReady', async () => {
      shareData && postMessageShare();
      !shareData &&
        h5uni.postMessage({
          data: {
            unshare: true,
          },
        });

      // 针对ios返回问题禁止返回事件
      h5uni.postMessage({
        data: {
          unSlide: true,
          Lock: true,
        },
      });
    });
  }
};

export const postMessageShare = (data) => {
  h5uni.postMessage({
    data: {
      share: data || shareData,
    },
  });
};

//注入UniJs
const initUniJS = () => {
  // <script src="https://lsol-house-upload.oss-cn-hangzhou.aliyuncs.com/2020-09-29wxls/yuanApp/uni/uni.js"></script>
  const loadScript = (options, callback) => {
    if (!options.src) {
      return;
    }
    // 判断引入的js对象是否存在
    if (typeof options.fun == 'undefined') {
      var node = document.createElement('script');
      node.src = options.src;
      node.addEventListener('load', callback, false);
      document.head.appendChild(node);
    } else {
      console.log('直接渲染');
      console.log(options.eventListener || 'load');
      document.addEventListener(options.eventListener || 'load', callback, false);
    }
  };
  loadScript(
    {
      src: `/${Constant.ROUTER_BASE}/static/js/uni.js`,
      fun: window.h5uni,
      eventListener: 'UniAppJSBridgeReady',
    },
    () => {},
  );
};
